package ch15;

import ch14.EmptyCollectionException;

/**
 * Created by 春旺 on 2017/10/13.
 */
public class CircularArrayQueue<T> implements Queue<T>
{
    private final int DEFAULT_CAPACITY = 10;
    private int front, rear, count;
    private T[] queue;
    //-----------------------------------------------------------------
// Creates an empty queue using the default capacity.
//-----------------------------------------------------------------
    public CircularArrayQueue()
    {
        front = rear = count = 0;
        queue = (T[]) (new Object[DEFAULT_CAPACITY]);
    }
    //-----------------------------------------------------------------
// Adds the specified element to the rear of this queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
    public void enqueue (T element)
    {
        if (count == queue.length)
            expandCapacity();
        queue[rear] = element;
        rear = (rear+1) % queue.length;
        count++;
    }

    @Override
    public T dequeue() throws EmptyCollectionException
    {
        T re =  queue[front];
        queue[front] = null;
        front = (front +1) % queue.length;
        count --;
        return re;
    }

    @Override
    public T first() {

        return queue[front];
    }

    @Override
    public boolean isEmpty() {
        boolean b = true;
        for(int i = 0;i< queue.length;i++){
            if (queue[i] != null){
                b = false;
                break;
            }
        }
        return b;
    }

    @Override
    public int size() {
        int size =count;
        return size;
    }

    //-----------------------------------------------------------------
// Creates a new array to store the contents of this queue with
// twice the capacity of the old one.
//-----------------------------------------------------------------
    public void expandCapacity()
    {
        T[] larger = (T[])(new Object[queue.length*2]);
        for (int index=0; index < count; index++)
            larger[index] = queue[(front+index) % queue.length];
        front = 0;
        rear = count;
        queue = larger;
    }
    @Override
    public String toString(){
        String result ="" ;
        if (count == 0)
            result = null;
        else
        for (int i= front;i < rear;i++){
            result += queue[i];
        }
        return result;
    }
}